package com.wangyadong.hobby.schedule.jobtask.thread;

import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.AbstractQueuedSynchronizer;
import java.util.stream.IntStream;

public class LimitLatch {

    private AtomicLong count;
    private volatile long limit;
    private Sync sync;

    public LimitLatch(long limit) {
        this.limit = limit;
        this.sync = new Sync();
        this.count = new AtomicLong();
    }

    private class Sync extends AbstractQueuedSynchronizer {
        @Override
        protected int tryAcquireShared(int arg) {
            long newCount = count.incrementAndGet();
            if (newCount > limit) {
                count.decrementAndGet();
                return -1;
            } else {
                return 1;
            }
        }

        @Override
        protected boolean tryReleaseShared(int arg) {
            count.decrementAndGet();
            return true;
        }
    }

    public void accquire() throws InterruptedException {
        sync.acquireSharedInterruptibly(1);
        System.out.println(Thread.currentThread().getName() + " get this lock");
    }

    public void release() {
        sync.releaseShared(0);
    }


    public static void main(String[] args) {
        LimitLatch limitLatch = new LimitLatch(2);
        IntStream.range(0, 5).forEach(i -> {
            new Thread(() -> {
                while (true) {
                    try {
                        limitLatch.accquire();
                        Thread.sleep(2000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    } finally {
                        limitLatch.release();
                    }
                }
            }).start();
        });
    }
}
